import 'dart:async';
import 'package:flutter/material.dart';
import 'bluetooth_service.dart';

class BluetoothExample extends StatefulWidget {
  const BluetoothExample({super.key});

  @override
  State<BluetoothExample> createState() => _BluetoothExampleState();
}

class _BluetoothExampleState extends State<BluetoothExample> {
  bool _isBluetoothAvailable = false;
  bool _isBluetoothEnabled = false;
  bool _hasPermission = false;
  bool _isLoading = false;
  bool _isScanning = false;
  String _connectionState = 'disconnected';
  BluetoothDevice? _currentDevice;
  List<BluetoothDevice> _pairedDevices = [];
  List<BluetoothDevice> _discoveredDevices = [];
  String _message = '';
  List<String> _receivedMessages = [];

  @override
  void initState() {
    super.initState();
    _initializeBluetooth();
    _setupBluetoothChannel();
  }

  void _setupBluetoothChannel() {
    // 设置蓝牙通道监听器
    BluetoothService.setupChannelListener();

    // 设置设备发现回调
    BluetoothService.setOnDeviceFound((device) {
      print('Flutter端收到设备发现事件: ${device.name} - ${device.address}');
      if (mounted) {
        setState(() {
          if (!_discoveredDevices.any((d) => d.address == device.address)) {
            _discoveredDevices.add(device);
            print('添加设备到列表，当前设备数: ${_discoveredDevices.length}');
          }
        });
      }
    });

    // 设置扫描开始回调
    BluetoothService.setOnDiscoveryStarted(() {
      if (mounted) {
        setState(() {
          _isScanning = true;
        });
      }
    });

    // 设置扫描完成回调
    BluetoothService.setOnDiscoveryFinished(() {
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
        _showInfoDialog('扫描完成，发现 ${_discoveredDevices.length} 个设备');
      }
    });
  }

  Future<void> _initializeBluetooth() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 检查蓝牙可用性
      final bool available = await BluetoothService.isBluetoothAvailable();
      setState(() {
        _isBluetoothAvailable = available;
      });

      if (available) {
        // 检查蓝牙是否启用
        final bool enabled = await BluetoothService.isBluetoothEnabled();
        setState(() {
          _isBluetoothEnabled = enabled;
        });

        // 检查权限
        final bool hasPermission =
            await BluetoothService.checkBluetoothPermissions();
        setState(() {
          _hasPermission = hasPermission;
        });

        if (enabled && hasPermission) {
          await _loadPairedDevices();
        }
      }
    } catch (e) {
      print('初始化蓝牙失败: $e');
      _showErrorDialog('初始化蓝牙失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _loadPairedDevices() async {
    try {
      final devices = await BluetoothService.getPairedDevices();
      setState(() {
        _pairedDevices = devices;
      });
    } catch (e) {
      print('获取配对设备失败: $e');
      if (e.toString().contains('PERMISSION_DENIED')) {
        _showPermissionDialog();
      }
    }
  }

  Future<void> _requestPermissions() async {
    try {
      setState(() {
        _isLoading = true;
      });

      final bool result = await BluetoothService.requestBluetoothPermissions();
      if (result) {
        _showInfoDialog('权限请求已发送，请允许权限后重试');
        // 延迟一下再检查权限状态
        Future.delayed(const Duration(seconds: 2), () {
          _checkPermissions();
        });
      }
    } catch (e) {
      _showErrorDialog('请求权限失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _checkPermissions() async {
    try {
      final bool hasPermission =
          await BluetoothService.checkBluetoothPermissions();
      setState(() {
        _hasPermission = hasPermission;
      });

      if (hasPermission) {
        await _loadPairedDevices();
      }
    } catch (e) {
      print('检查权限失败: $e');
    }
  }

  Future<void> _enableBluetooth() async {
    try {
      setState(() {
        _isLoading = true;
      });

      final bool result = await BluetoothService.enableBluetooth();
      if (result) {
        setState(() {
          _isBluetoothEnabled = true;
        });
        await _loadPairedDevices();
        _showInfoDialog('蓝牙已启用');
      }
    } catch (e) {
      _showErrorDialog('启用蓝牙失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _startScan() async {
    try {
      setState(() {
        _discoveredDevices.clear();
      });

      print('开始扫描蓝牙设备...');
      final bool result = await BluetoothService.startScan();
      print('扫描启动结果: $result');

      if (result) {
        _showInfoDialog('开始扫描设备，请稍等...');
      } else {
        _showErrorDialog('启动扫描失败');
      }
    } catch (e) {
      print('扫描失败: $e');
      _showErrorDialog('开始扫描失败: $e');
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
      }
    }
  }

  Future<void> _stopScan() async {
    try {
      await BluetoothService.stopScan();
      _showInfoDialog('扫描已停止');
    } catch (e) {
      _showErrorDialog('停止扫描失败: $e');
    }
  }

  Future<void> _connectDevice(BluetoothDevice device) async {
    try {
      setState(() {
        _isLoading = true;
        _connectionState = 'connecting';
      });

      // 检查设备是否已配对
      final isPaired = _pairedDevices.any((d) => d.address == device.address);

      if (!isPaired) {
        // 只有未配对的设备才需要配对
        print('设备未配对，开始配对: ${device.name}');
        await _pairDevice(device);
      } else {
        print('设备已配对，直接连接: ${device.name}');
      }

      final bool result = await BluetoothService.connectDevice(device.address);
      if (result) {
        setState(() {
          _connectionState = 'connected';
          _currentDevice = device;
        });
        _showInfoDialog('已连接到 ${device.name}');
      } else {
        setState(() {
          _connectionState = 'error';
        });
        _showErrorDialog('连接失败，请检查设备是否支持串口通信');
      }
    } catch (e) {
      setState(() {
        _connectionState = 'error';
      });

      String errorMessage = '连接设备失败: $e';
      if (e.toString().contains('CONNECTION_FAILED')) {
        errorMessage =
            '无法连接到设备，该设备不支持串口通信！\n\n'
            '❌ 不支持：手机、耳机、手表、音响等\n'
            '✅ 支持：蓝牙模块（HC-05、HC-06）、Arduino、ESP32等\n\n'
            '请尝试连接支持SPP协议的蓝牙设备';
      } else if (e.toString().contains('PERMISSION_DENIED')) {
        errorMessage = '权限不足，请检查蓝牙权限设置';
      } else if (e.toString().contains('timeout')) {
        errorMessage = '连接超时，请重试或检查设备状态';
      }

      _showErrorDialog(errorMessage);
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _pairDevice(BluetoothDevice device) async {
    try {
      print('开始配对设备: ${device.name}');
      final bool result = await BluetoothService.pairDevice(device.address);
      if (result) {
        print('设备配对成功: ${device.name}');
        _showInfoDialog('设备 ${device.name} 配对成功');
      } else {
        print('设备配对失败: ${device.name}');
        _showErrorDialog('设备配对失败，请重试');
      }
    } catch (e) {
      print('配对设备异常: $e');
      _showErrorDialog('配对设备失败: $e');
    }
  }

  Future<void> _disconnect() async {
    try {
      setState(() {
        _isLoading = true;
      });

      await BluetoothService.disconnect();
      setState(() {
        _connectionState = 'disconnected';
        _currentDevice = null;
      });
      _showInfoDialog('已断开连接');
    } catch (e) {
      _showErrorDialog('断开连接失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _sendMessage() async {
    if (_message.trim().isEmpty) {
      _showErrorDialog('请输入要发送的消息');
      return;
    }

    try {
      final bool result = await BluetoothService.sendData(_message);
      if (result) {
        setState(() {
          _receivedMessages.add('发送: $_message');
          _message = '';
        });
        _showInfoDialog('消息发送成功');
      }
    } catch (e) {
      _showErrorDialog('发送消息失败: $e');
    }
  }

  Future<void> _readMessage() async {
    try {
      final String data = await BluetoothService.readData();
      if (data.isNotEmpty) {
        setState(() {
          _receivedMessages.add('接收: $data');
        });
      } else {
        _showInfoDialog('没有接收到数据');
      }
    } catch (e) {
      _showErrorDialog('读取消息失败: $e');
    }
  }

  Future<void> _testConnection() async {
    try {
      setState(() {
        _isLoading = true;
      });

      // 检查蓝牙状态
      final bool available = await BluetoothService.isBluetoothAvailable();
      final bool enabled = await BluetoothService.isBluetoothEnabled();
      final bool hasPermission =
          await BluetoothService.checkBluetoothPermissions();

      String statusMessage = '蓝牙诊断结果:\n\n';
      statusMessage += '蓝牙可用: ${available ? "是" : "否"}\n';
      statusMessage += '蓝牙启用: ${enabled ? "是" : "否"}\n';
      statusMessage += '权限状态: ${hasPermission ? "已授权" : "需要权限"}\n';

      if (available && enabled && hasPermission) {
        final devices = await BluetoothService.getPairedDevices();
        statusMessage += '已配对设备: ${devices.length}个\n';

        if (devices.isNotEmpty) {
          statusMessage += '\n设备列表:\n';
          for (var device in devices) {
            statusMessage += '• ${device.name} (${device.address})\n';
          }
        } else {
          statusMessage += '\n建议: 请先在系统设置中配对蓝牙设备';
        }
      } else {
        statusMessage += '\n建议: 请启用蓝牙并授予权限';
      }

      _showInfoDialog(statusMessage);
    } catch (e) {
      _showErrorDialog('测试连接失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showPermissionDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('需要权限'),
          content: const Text(
            '此功能需要蓝牙权限才能正常工作。\n\n'
            '请点击"请求权限"按钮，然后在权限设置中允许蓝牙权限。',
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                _requestPermissions();
              },
              child: const Text('请求权限'),
            ),
          ],
        );
      },
    );
  }

  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('错误'),
          content: Text(message),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showInfoDialog(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示'),
          content: Text(message),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  String _getConnectionStateText() {
    switch (_connectionState) {
      case 'disconnected':
        return '未连接';
      case 'connecting':
        return '连接中...';
      case 'connected':
        return '已连接';
      case 'error':
        return '连接错误';
      default:
        return '未知状态';
    }
  }

  Color _getConnectionStateColor() {
    switch (_connectionState) {
      case 'disconnected':
        return Colors.grey;
      case 'connecting':
        return Colors.orange;
      case 'connected':
        return Colors.green;
      case 'error':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('蓝牙连接演示'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 蓝牙状态
            _buildStatusSection(),
            const SizedBox(height: 16),

            // 使用说明
            _buildUsageInstructions(),
            const SizedBox(height: 16),

            // 蓝牙控制
            _buildControlSection(),
            const SizedBox(height: 16),

            // 设备列表
            if (_pairedDevices.isNotEmpty || _discoveredDevices.isNotEmpty)
              _buildDeviceSection(),

            // 连接控制
            if (_connectionState == 'connected') _buildConnectionSection(),

            // 数据传输
            if (_connectionState == 'connected') _buildDataTransferSection(),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '蓝牙状态',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            _buildStatusRow(
              '蓝牙可用',
              _isBluetoothAvailable ? '是' : '否',
              _isBluetoothAvailable ? Colors.green : Colors.red,
            ),
            _buildStatusRow(
              '蓝牙启用',
              _isBluetoothEnabled ? '是' : '否',
              _isBluetoothEnabled ? Colors.green : Colors.red,
            ),
            _buildStatusRow(
              '权限状态',
              _hasPermission ? '已授权' : '需要权限',
              _hasPermission ? Colors.green : Colors.orange,
            ),
            _buildStatusRow(
              '连接状态',
              _getConnectionStateText(),
              _getConnectionStateColor(),
            ),
            if (_currentDevice != null)
              _buildStatusRow('当前设备', _currentDevice!.name, Colors.blue),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusRow(String label, String value, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontSize: 14)),
          Text(
            value,
            style: TextStyle(
              fontSize: 14,
              color: color,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildControlSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '蓝牙控制',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                if (!_isBluetoothEnabled)
                  ElevatedButton(
                    onPressed: _isLoading ? null : _enableBluetooth,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                    ),
                    child: const Text(
                      '启用蓝牙',
                      style: TextStyle(color: Colors.white),
                    ),
                  )
                else ...[
                  ElevatedButton(
                    onPressed: _isLoading
                        ? null
                        : (_isScanning ? _stopScan : _startScan),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _isScanning ? Colors.red : Colors.green,
                    ),
                    child: Text(
                      _isScanning ? '停止扫描' : '开始扫描',
                      style: const TextStyle(color: Colors.white),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _loadPairedDevices,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.orange,
                    ),
                    child: const Text(
                      '刷新设备',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _requestPermissions,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.purple,
                    ),
                    child: const Text(
                      '请求权限',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _testConnection,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.teal,
                    ),
                    child: const Text(
                      '测试连接',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ],
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDeviceSection() {
    final allDevices = [..._pairedDevices, ..._discoveredDevices];

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '设备列表 (${allDevices.length})',
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                if (_isScanning)
                  const Row(
                    children: [
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                      SizedBox(width: 8),
                      Text('扫描中...', style: TextStyle(fontSize: 12)),
                    ],
                  ),
              ],
            ),
            const SizedBox(height: 12),

            // 已配对设备
            if (_pairedDevices.isNotEmpty) ...[
              Row(
                children: [
                  const Icon(
                    Icons.bluetooth_connected,
                    size: 16,
                    color: Colors.blue,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '已配对设备 (${_pairedDevices.length})',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              ..._pairedDevices.map((device) => _buildDeviceItem(device)),
              const SizedBox(height: 16),
            ],

            // 发现的设备
            if (_discoveredDevices.isNotEmpty) ...[
              Row(
                children: [
                  const Icon(
                    Icons.bluetooth_searching,
                    size: 16,
                    color: Colors.green,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '发现的设备 (${_discoveredDevices.length})',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.green,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              ..._discoveredDevices.map((device) => _buildDeviceItem(device)),
            ],

            // 扫描状态提示
            if (_isScanning && _discoveredDevices.isEmpty)
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    ),
                    SizedBox(width: 8),
                    Text('正在搜索附近的蓝牙设备...'),
                  ],
                ),
              ),

            // 没有设备时的提示
            if (!_isScanning && allDevices.isEmpty)
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Icon(
                      Icons.bluetooth_disabled,
                      size: 48,
                      color: Colors.grey,
                    ),
                    SizedBox(height: 8),
                    Text('没有找到蓝牙设备', style: TextStyle(color: Colors.grey)),
                    SizedBox(height: 4),
                    Text(
                      '请确保设备已开启蓝牙并处于可发现状态',
                      style: TextStyle(fontSize: 12, color: Colors.grey),
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildDeviceItem(BluetoothDevice device) {
    final isConnected =
        _connectionState == 'connected' &&
        _currentDevice?.address == device.address;

    // 检查设备是否支持串口通信
    final isSerialDevice = _isSerialCapableDevice(device);

    return ListTile(
      title: Text(device.name),
      subtitle: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('${device.address} - ${device.type}'),
          if (!isSerialDevice)
            const Text(
              '⚠️ 此设备可能不支持串口通信',
              style: TextStyle(color: Colors.orange, fontSize: 12),
            ),
        ],
      ),
      trailing: isConnected
          ? const Text(
              '已连接',
              style: TextStyle(
                color: Colors.green,
                fontWeight: FontWeight.bold,
              ),
            )
          : Text(
              isSerialDevice ? '连接' : '尝试连接',
              style: TextStyle(
                color: isSerialDevice ? Colors.blue : Colors.orange,
              ),
            ),
      onTap: isConnected ? null : () => _connectDevice(device),
    );
  }

  bool _isSerialCapableDevice(BluetoothDevice device) {
    // 过滤掉常见的非串口设备
    final nonSerialDevices = [
      'FreeBuds',
      'AirPods',
      'Headphones',
      'Earphones',
      'Watch',
      'GT',
      'Mate',
      'P40',
      'P50',
      'P60',
      'iPhone',
      'Samsung',
      'Xiaomi',
      'Oppo',
      'Vivo',
      'Speaker',
      '音响',
      '音箱',
      '耳机',
      '手表',
      '手环',
    ];

    final deviceName = device.name.toLowerCase();
    for (final nonSerialDevice in nonSerialDevices) {
      if (deviceName.contains(nonSerialDevice.toLowerCase())) {
        return false;
      }
    }

    return true;
  }

  Widget _buildUsageInstructions() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '使用说明',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            const Text('此功能用于连接支持串口通信的蓝牙设备，如：', style: TextStyle(fontSize: 14)),
            const SizedBox(height: 8),
            const Text(
              '✅ 蓝牙模块（HC-05、HC-06等）\n'
              '✅ Arduino开发板\n'
              '✅ 蓝牙串口适配器\n'
              '✅ 支持SPP协议的设备',
              style: TextStyle(fontSize: 14, color: Colors.green),
            ),
            const SizedBox(height: 8),
            const Text(
              '❌ 不支持：耳机、手表、音响等音频设备',
              style: TextStyle(fontSize: 14, color: Colors.red),
            ),
            const SizedBox(height: 8),
            const Text(
              '💡 提示：请先在系统设置中配对支持串口通信的设备',
              style: TextStyle(fontSize: 14, color: Colors.blue),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildConnectionSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '连接控制',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _isLoading ? null : _disconnect,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                child: const Text(
                  '断开连接',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDataTransferSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '数据传输',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            TextField(
              decoration: const InputDecoration(
                labelText: '输入要发送的消息',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
              controller: TextEditingController(text: _message),
              onChanged: (value) => setState(() => _message = value),
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: _sendMessage,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                    ),
                    child: const Text(
                      '发送',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _readMessage,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                    ),
                    child: const Text(
                      '读取',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
            if (_receivedMessages.isNotEmpty) ...[
              const SizedBox(height: 16),
              const Text(
                '消息记录:',
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              ..._receivedMessages.map(
                (msg) => Padding(
                  padding: const EdgeInsets.symmetric(vertical: 2.0),
                  child: Text(msg, style: const TextStyle(fontSize: 12)),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
